import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import { getCookie } from '@/utils/common'
import { LoadingBar } from 'view-design'

// 免登录白名单
const whiteList = ['/login']

Vue.use(Router)

// 重写push方法，添加catch
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 基础路由
export const constantRoutes = [
  {
    path: '/login',
    meta: {
      title: '登录'
    },
    component: () => import('@/views/login')
  }, {
    path: '*',
    meta: {
      title: '404'
    },
    component: () => import('@/views/error/404')
  }
]

const router = new Router({
  mode: 'history',
  routes: constantRoutes
})

router.beforeEach((to, from, next) => {
  LoadingBar.start();
  if (getCookie('token')) {
    if (to.path === '/login') {
      next()
    } else {
      if (store.getters['router/addRoutesEmpty']) {
        store.dispatch('router/generateRouter').then(res => {
          router.addRoute(...res) // 动态添加可访问路由表
          // 动态添加可访问路由表
          next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
          LoadingBar.finish();
        })
      } else {
        // 获取菜单中的按钮权限
        !store.getters['router/getMenuList'](to.meta.menuId).length && to.meta.menuId && store.dispatch('router/getMenuButtons', { 'menuId': to.meta.menuId })
        if (to.path == '/') {
          next(store.state.router.firstRoutes)
        } else next()
        LoadingBar.finish();
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      // 否则全部重定向到登录页
      next('/login')
    }
    LoadingBar.finish();
  }
})

router.afterEach((to) => {
  to.meta.title && (document.title = to.meta.title);
  to.meta.menuId && store.dispatch('router/setPageBtn', store.getters['router/getMenuList'](to.meta.menuId))
  LoadingBar.finish();
});

export default router